<template>
    <basic-container>
        <avue-crud v-if="!showiteminfo" :option="option" v-model:search="search" v-model:page="page" v-model="form"
            :table-loading="loading" :data="data" :permission="permissionList" :before-open="beforeOpen" ref="crud"
            @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel" @search-change="searchChange"
            @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange"
            @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
            <template #menu-left>
                <el-button type="primary" icon="el-icon-upload" @click="excelBox = true">导入
                </el-button>
                <el-button type="danger" icon="el-icon-delete" plain v-if="permission.qyClasses_delete"
                    @click="handleDelete">删 除
                </el-button>
                <el-button type="warning" plain icon="el-icon-download" @click="handleExport">导 出
                </el-button>
            </template>
            <template #menu="{ row, index, size }">
                <el-button type="primary" size="small" icon="el-icon-view" @click="showinfo(row, index)">详情</el-button>
            </template>

            <template #lessonSchedules="scope">
                <div style="display:block;">                  
                  <div v-for="item in scope.row.lessonSchedules">{{item}}</div>
                </div> 
            </template>

             
        </avue-crud>

        <div v-if="showiteminfo">
            <div>
                <el-button size="small" @click="showiteminfo = false">返回</el-button>

                <div style="font-size:23px;margin-top: 20px;">
                    {{ selRow.name }} <span
                        style="font-size:15px;background-color:blue;color: #FFF; padding:2px 2px;border-radius: 4px;">{{
            selRow.$type }}</span>
                </div>
                <div style="">
                    <div style="line-height: 35px; display: flex;">
                        <div> 授课课程:未设置 </div>
                        <div> 最大容量(人):未设置 </div>
                        <div> 备注:未设置 </div>
                    </div>
                    <div style="line-height:35px; display: flex;">
                        <div> 默认老师:未设置 </div>
                        <div> 教室:未设置 </div>
                        <div> 默认课时数:未设置 </div>
                    </div>

                    <div style="display: flex; font-size: 15px; line-height: 35px;">约课模式 : <avue-switch v-model="yymode"
                            :dic="dic"></avue-switch> &emsp;<span style=" font-size: 14px; color:blue;">修改</span> &emsp;
                        <div v-if="yymode">
                            <div>
                                约课开始时间： 上课开始前18小时 约课锁定时间： 上课开始前18小时 到锁定时间人数少则自动取消： 关
                            </div>
                        </div>
                    </div>
                    <el-divider />
                    <div style="font-weight:700; display: flex;justify-content: space-between;">课表 
                        <el-button type="primary" size="large"   @click="showLessonAdd()">创建课表</el-button></div>
                    <div v-for="item in cuurentCLList" >
                        <div v-if="item.repetitive == 0">日期 {{ item.startTime }} {{ item.subStartTime }}-{{  item.subEndTime }}
                            <div style="display: flex; line-height: 35px; width: 500px; justify-content: space-between; ">
                                <div>{{ item.teacherNames }} {{ item.roomName }}</div>
                                <div>
                                    <el-button type="primary" size="small" icon="el-icon-edit" @click="showLessonEdit(item)"></el-button>
                                    <el-button type="primary" size="small" icon="el-icon-edit" @click="showLessonEdit(item)"></el-button>
                                </div> 
                            </div>
                     
                        </div>
                        <div v-if="item.repetitive == 1">每天 {{ item.subStartTime }}-{{ item.subEndTime }} 从 {{  item.startTime }} 至{{ item.endTime }}
                            <div style="display: flex; line-height: 35px; width: 500px; justify-content: space-between; ">
                                <div>{{ item.teacherNames }} {{ item.roomName }}</div>
                                <div>
                                    <el-button type="primary" size="small" icon="el-icon-edit" @click="showLessonEdit(item)"></el-button>
                                    <el-button type="primary" size="small" icon="el-icon-edit" @click="showLessonEdit(item)"></el-button>
                                </div> 
                            </div>
                        </div>
                        <div  v-if="item.repetitive == 2">每周{{ weekmap.get(item.rate) }}的 {{ item.subStartTime }}-{{ item.subEndTime }} 从 {{ item.startTime }}至 {{ item.endTime }}
                            <div style="display: flex;line-height: 35px;  width: 500px; justify-content: space-between; ">
                                <div>{{ item.teacherNames }} {{ item.roomName }}</div>
                                <div>
                                    <el-button type="primary" size="small" icon="el-icon-edit" @click="showLessonEdit(item)"></el-button>
                                    <el-button type="primary" size="small" icon="el-icon-edit" @click="showLessonEdit(item)"></el-button>
                                </div> 
                            </div>
                        </div>
                    </div>

                    <div style="font-weight:700; line-height:50px;">课表列表</div>
                    <qyClassesLessonsDetails :classes_id=this.selRow.id></qyClassesLessonsDetails>
                    <div>

                    </div>

                </div>
            </div> 
        </div>
    </basic-container>

    <el-dialog title="导入班级数据" append-to-body v-model="excelBox0" width="555px">
        <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter1">
        </avue-form>
    </el-dialog>


    <el-dialog title="添加课表" append-to-body v-model="excelBox" width="800px">
        <div style="
        display: flex;
        width: 100%;
        text-align: center;
        align-items: center;
        justify-content: center;
      ">
            <div style="text-align: left; width: 450px">
                <avue-form ref="lessonsfrom" :option="addoption" v-model="lessonsfrom" @submit="handleLessonAddSubmit">
                </avue-form>
            </div>
        </div>
    </el-dialog>

    <el-dialog title="编辑课表" append-to-body v-model="excelBox1" width="800px">
        <div style="
        display: flex;
        width: 100%;
        text-align: center;
        align-items: center;
        justify-content: center;
      ">
            <div style="text-align: left; width: 450px">
                <avue-form :option="editoption" v-model="lessonsfrom" @submit="handleLessonEditSubmit">
                </avue-form>
            </div>
        </div>
    </el-dialog>

</template>

<script>
import { getList, getDetail, add, update, remove } from "@/api/classes/qyClasses";
 
import { getCLList,addLesson } from '@/api/classes/qyClassesLessons';
import option from "@/option/classes/qyClasses";
import addoption from '@/option/classes/qyClassesLessonsAdd';
import editoption from '@/option/classes/qyClassesLessonsEdit';

import { mapGetters } from "vuex";
import { exportBlob } from "@/api/common";
import { getToken } from '@/utils/auth';
import { downloadXls } from "@/utils/util";
import { dateNow } from "@/utils/date";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

import qyClassesLessons from './qyClassesLessons.vue';
import qyClassesLessonsDetails from './qyClassesLessonsDetails.vue';


export default {
    components: {
        qyClassesLessons,
        qyClassesLessonsDetails
    },

    data() {
        return {
            form: {},
            query: {},
            search: {},
            loading: true,
            weekmap: new Map(),
            page: {
                pageSize: 10,
                currentPage: 1,
                total: 0
            },
            yymode: 1,
            dic: [{
                label: '开',
                value: 0
            }, {
                label: '关',
                value: 1
            }],
            showiteminfo: false,
            cuurentCLList: [],
            selectionList: [],
            option: option,
            excelBox0: false,
            excelForm: {},
            excelOption: {
                submitBtn: false,
                emptyBtn: false,
                column: [
                    {
                        label: '',
                        prop: 'excelFile',
                        type: 'upload',
                        drag: true,
                        loadText: '数据上传中，请稍等',
                        span: 24,
                        propsHttp: {
                            res: 'data',
                        },
                        tip: '请上传 .xls,.xlsx 标准格式文件',
                        action: '/xrsk-qyClasses/qyClasses/import-classes',
                    }
                ]
            },
            selRow: {},


            display: false,
            excelBox: false,
            excelBox1: false,
            dicData: [],
            addoption: addoption,
            editoption: editoption,
            lessonsfrom: {},

            data: []
        };
    },
    computed: {
        ...mapGetters(["permission"]),
        permissionList() {
            return {
                addBtn: this.validData(this.permission.qyClasses_add, false),
                viewBtn: this.validData(this.permission.qyClasses_view, false),
                delBtn: this.validData(this.permission.qyClasses_delete, false),
                editBtn: this.validData(this.permission.qyClasses_edit, false)
            };
        },
        ids() {
            let ids = [];
            this.selectionList.forEach(ele => {
                ids.push(ele.id);
            });
            return ids.join(",");
        }
    },
    methods: {
        showinfo(row, index) {
            this.selRow = row;
            const value = { classesId: row.id }
            getCLList(0, 10000,value).then((res) => {
                this.cuurentCLList = res.data.data.records; 
            })
            this.showiteminfo = true;
        },
        reloadInfo(){
          const value = { classesId: this.selRow.id }
          getCLList(0, 10000,value).then((res) => {
                this.cuurentCLList = res.data.data.records; 
          })
        },
        showLessonAdd() {
            this.lessonsfrom = {};
            this.lessonsfrom.classesId = this.selRow.id; 
            this.excelBox = !this.excelBox;
        },
        showLessonEdit(row) {
            this.lessonsfrom = row;
            
            this.excelBox1 = true;
        },
        handleLessonAddSubmit(form, done) {
            this.$refs.lessonsfrom.validate(valid => {
                if (valid) {
                    let obj = { ...form };
                    if (obj.teacherIds instanceof Array) {
                        if (obj.teacherIds.length > 0) {
                            obj.teacherIds = obj.teacherIds.join(',');
                        } else {
                            obj.teacherIds = '';
                        }
                    }

                    obj.startTime = obj.startTime + ' 00:00:00';
                    obj.endTime = obj.endTime + ' 00:00:00';

                    addLesson(obj).then(
                        () => {
                            this.onLoad(this.page);
                            this.$message({
                                type: 'success',
                                message: '操作成功!',
                            });
                            this.excelBox = false;
                            this.reloadInfo();
                            done();
                           
                        },
                        error => {
                            // loading();
                            window.console.log(error);
                        }
                    );
                }
            });
            done();
        },
        handleLessonEditSubmit(form, done) {

            let obj = { ...form };
            if (obj.teacherIds instanceof Array) {
                if (obj.teacherIds.length > 0) {
                    obj.teacherIds = obj.teacherIds.join(',');
                } else {
                    obj.teacherIds = '';
                }
            }

            obj.startTime = obj.startTime + ' 00:00:00';
            obj.endTime = obj.endTime + ' 00:00:00';

            addLesson(obj).then(
                () => {
                    this.onLoad(this.page);
                    this.$message({
                        type: 'success',
                        message: '操作成功!',
                    });
                    this.excelBox1 = false;
                    this.reloadInfo();
                    done();
                    
                },
                error => {
                    // loading();
                    window.console.log(error);
                }
            );


        },
        uploadAfter1(res, done, loading, column) {
            done();
            this.$message.warning(res);
            this.excelBox0 = false;
        },
        rowSave(row, done, loading) {
            add(row).then(() => {
                this.onLoad(this.page);
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
                done();
            }, error => {
                loading();
                window.console.log(error);
            });
        },
        rowUpdate(row, index, done, loading) {
            update(row).then(() => {
                this.onLoad(this.page);
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
                done();
            }, error => {
                loading();
                console.log(error);
            });
        },
        rowDel(row) {
            this.$confirm("确定将选择数据删除?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    return remove(row.id);
                })
                .then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                });
        },
        handleDelete() {
            if (this.selectionList.length === 0) {
                this.$message.warning("请选择至少一条数据");
                return;
            }
            this.$confirm("确定将选择数据删除?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    return remove(this.ids);
                })
                .then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    this.$refs.crud.toggleSelection();
                });
        },
        handleExport() {
            let downloadUrl = `/xrsk-qyClasses/qyClasses/export-qyClasses?${this.website.tokenHeader}=${getToken()}`;
            const {
            } = this.query;
            let values = {
            };
            this.$confirm("是否导出数据?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                NProgress.start();
                exportBlob(downloadUrl, values).then(res => {
                    downloadXls(res.data, `班级管理${dateNow()}.xlsx`);
                    NProgress.done();
                })
            });
        },
        beforeOpen(done, type) {
            if (["edit", "view"].includes(type)) {
                getDetail(this.form.id).then(res => {
                    this.form = res.data.data;
                });
            }
            done();
        },
        searchReset() {
            this.query = {};
            this.onLoad(this.page);
        },
        searchChange(params, done) {
            this.query = params;
            this.page.currentPage = 1;
            this.onLoad(this.page, params);
            done();
        },
        selectionChange(list) {
            this.selectionList = list;
        },
        selectionClear() {
            this.selectionList = [];
            this.$refs.crud.toggleSelection();
        },
        currentChange(currentPage) {
            this.page.currentPage = currentPage;
        },
        sizeChange(pageSize) {
            this.page.pageSize = pageSize;
        },
        refreshChange() {
            this.onLoad(this.page, this.query);
        },
        onLoad(page, params = {}) {
            this.weekmap.set(1, "一");
            this.weekmap.set(2, "二");
            this.weekmap.set(3, "三");
            this.weekmap.set(4, "四");
            this.weekmap.set(5, "五");
            this.weekmap.set(6, "六");
            this.weekmap.set(7, "日");
            this.loading = true;

            const {
            } = this.query;

            let values = {
            };

            getList(page.currentPage, page.pageSize, values).then(res => {
                const data = res.data.data;
                this.page.total = data.total;
                this.data = data.records;
                this.loading = false;
                this.selectionClear();
            });
        }
    }
};
</script>

<style></style>
